/**
 * @file 工单操作-改预付款
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer','form','laydate','upload','list_modify_common', '$http'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var opCommonUtils = layui.list_modify_common;
    var $http = layui.$http;
    var laydate = layui.laydate;
    let upload = layui.upload;
    let timestamp = new Date().getTime();

    Number.prototype.div = function (arg) {
        var t1 = 0, t2 = 0, r1, r2;
        try {
            t1 = this.toString().split(".")[1].length
        } catch (e) {
        }
        try {
            t2 = arg.toString().split(".")[1].length
        } catch (e) {
        }
        with (Math) {
            r1 = Number(this.toString().replace(".", ""));
            r2 = Number(arg.toString().replace(".", ""));
            return (r1 / r2) * pow(10, t2 - t1);
        }
    };
    /**
     * 提示框
     * @param str {string} 提示内容;
     * @returns {*}
     */
    function toast(str) {
        return layer.msg(str);
    }

    /**
     * 分转元
     * @param numstr
     * @returns {*}
     * @constructor
     */

    function Fen2Yuan(numstr) {
        var num = Number(numstr);
        return (num.div(100)).toFixed(2);
    }

    /**
     * 判断是否是正整数且最多小数点后两位;
     * @param val {number/string} 字符串或数字
     * @returns {boolean} 返回是否是数字
     */
    function isNumber(val) {
        var reg = /^[0-9]+([.]{1}[0-9]{1,2})?$/;//正整数到小数点后两位
        return reg.test(val);
    }

    /**
     * 描述: 图片上传方法
     * @param elemId
     * @param valueId
     */
     let indexUploadImags;
     function uploaderImage(elemId, valueId) {
       upload.render({
            elem: '#' + elemId
            , exts: 'jpg|png|jpeg'
            , acceptMime: 'image/*'
            , accept: 'images'
            , url: '/work/modify/uploader/orderPhoto?timestamp=' + timestamp + '&elemId=' + elemId
            , size: 5120
            , beforeSend: function (obj) {
                indexUploadImags = layui.layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            }
            , done: function (res) {
                 if (res.status == 200) {
                        var data = res.data;
                        $("#" + valueId).val(data);
                        $("#" + valueId+"s").attr("src",data).attr("style", "width: 0;height: 0");
                        reLoadImage(elemId, data);
                    } else {
                        layer.msg(res.message)
                    }
                    layui.layer.close(indexUploadImags);
            }
       });
     }

    function reLoadImage(elemId, value, valueId) {
         zmnUploadUtil.reLoadImage($, elemId, value, valueId);
         let next = $("#" + elemId + "Value").next();
         let next1 = $(next).next();
         $(next).attr("style", "visibility:hidden !important");
         $(next1).attr("style", "visibility:hidden !important");
    }

    function submit(data) {
        data.field['channelPrepayAmount'] = (Number(data.field['channelPrepayAmount']) * 100).toFixed(0);
        data.field['remove'] = data.field['remove'] ? data.field['remove'] : 1;

        if(data.field.remove === 1){
           if(data.field.channelPrepayCertificateSrc == null || data.field.channelPrepayCertificateSrc === ''){
              layer.msg("请上传改预付款凭证图片");
              return false;
            }
        }

        var prepayAmountDetailItemList = [];
        $('.prepay-amount-item').each(function () {
            let $this = $(this);
            let itemAmount = $this.val();
            if (itemAmount && itemAmount.trim().length > 0) {
                prepayAmountDetailItemList.push({
                    text: $this.parent().prev().text(),
                    value: opCommonUtils.accMul(itemAmount, 100)
                });
                data.field['channelPrepayAmount'] = opCommonUtils.accAdd(data.field['channelPrepayAmount'], opCommonUtils.accMul(itemAmount, 100));
            }
        });

        // 总金额不能大于订单金额
        if (data.field['channelPrepayAmount'] > channelPrepayAmount.maxPrepayAmount) {
            var maxValue = Fen2Yuan(channelPrepayAmount.maxPrepayAmount);
            layer.msg("不能大于" + maxValue);
            return false;
        }

        data.field.channelPrepayAmountDetailList = prepayAmountDetailItemList;

        var url = data.form.action;
        $http.lockSave(url, data.field, data.elem).then(function () {
            layer.msg('操作成功', {icon: 1, time: 1000}, function () {
                opCommonUtils.goOperateHome();
            });
        }, function (msg) {
            layer.msg(msg);
        });
    }
    /**
     * 初始化页面
     */
    function initPage () {
        if (channelPrepayAmount.channelPrepayAmount) {
            $('input[name=channelPrepayAmount]').val(Fen2Yuan(channelPrepayAmount.channelPrepayAmount ));
        }
        uploaderImage("channelPrepayCertificateImgSrc", "channelPrepayCertificateImgSrcValue");

        // 回显已有图片
        let imageSrc = channelPrepayAmount.channelPrepayCertificateSrc;
        if (imageSrc) {
            let imageSrcArr = imageSrc.split(",");
            imageSrcArr.forEach(function (url, index) {
                reLoadImage("channelPrepayCertificateImgSrc", url);
                $("#channelPrepayCertificateImgSrcValue").val(url);
                $("#channelPrepayCertificateImgSrcValues").attr("src",url).attr("style", "width: 0;height: 0");
            })
        }
    }

    /**
     * 初始化页面事件
     */
    function initEvent () {
        //保存
        form.on('submit()', function (data) {
            submit(data);
            return false
        });
        //监听预付款框
        form.verify({
            "user-number":function (val) {
                if(val > 10000000){
                    return "不能大于一千万"
                }
                var maxValue = Fen2Yuan(channelPrepayAmount.maxPrepayAmount);
                if(val * 100 > channelPrepayAmount.maxPrepayAmount){
                    return "不能大于订单收入：" + maxValue + "元";
                }
                if(!isNumber(val)){
                    return "请输入正整数且最多保留两位小数"
                }
            },
            "channel-amount":function (val) {
                if(val > 10000000){
                    return "不能大于一千万"
                }
                if (val) {
                    if (!isNumber(val)) {
                        return "请输入正整数且最多保留两位小数"
                    }
                }
            }
        })

        // 点击删除图片
        $(document).on('click', '.btn-delete', function () {
            let $uploadDiv = $(this).parent().prev().prev();
            $uploadDiv.attr("style", "");
            $uploadDiv.find(".layui-upload-drag").attr("style", "");
            $uploadDiv.find("i").attr("style", "");
            $uploadDiv.find("p").attr("style", "");
            $uploadDiv.find(":hidden").val("");
            $uploadDiv.find("img").prop("src", "");
        });
        // 点击放大
        $(document).on('click', '.btn-review', function () {
            if (!$(this).parent().prev().prev().find("input").eq(0).val()) {
                layer.msg("请上传对应图片再预览");
                return;
            }
            let $container = $(this).parent().prev().prev().find("img").eq(0);
            $container.viewer().on('hide', function () {
                $container.viewer('destroy');
            });
            let index = $(this).index();
            $container.viewer('view', index);
        });
    }

    // 程序入口
    function init () {

      // 初始化页面
      initPage();

      // 初始化事件
      initEvent();

    }

    // 初始化
    init();
    exports('oms_work_modify_channelprepayamount');
});
